package com.example.tangyee.utils;

import android.os.AsyncTask;
import android.util.Log;

import com.example.tangyee.bean.Recipe;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetRecipes extends AsyncTask<Void, Void, List<Recipe>> {

    private static final String TAG = "GetRecipes";

    private int page;
    private int pageSize;
    private OnPostExecute mExecute;

    public GetRecipes(int page, int pageSize, OnPostExecute execute){
        this.page = page;
        this.pageSize = pageSize;
        this.mExecute = execute;
    }

    @Override
    protected List<Recipe> doInBackground(Void... voids) {
        if (isCancelled()) {
            return new ArrayList<>();
        }
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(false)
                .build();

        StringBuilder stringBuilder = new StringBuilder(ConstantsUtil.GET_RECIPES);
        stringBuilder.append("page=" + page);
        stringBuilder.append("&pagesize=" + pageSize);
        Log.d(TAG, "doInBackground: " + stringBuilder.toString());
        Request request = new Request.Builder()
                .url(stringBuilder.toString())
                .build();

        String respStr = null;
        try {
            Response response = okHttpClient.newCall(request).execute();
            respStr = response.body().string();
        } catch (IOException e) {
            Log.e(TAG, "doInBackground: ", e);
        }
        List<Recipe> items = new ArrayList<>();

        try {
            Log.i(TAG, "Received JSON: " + respStr);
            if (respStr == null) {
                /*
                * java.net.SocketTimeoutException: timeout   -->   Response response = okHttpClient.newCall(request).execute();
                *
                * 03-03 15:25:27.493 19399-19424/com.example.tangyee I/GetRecipes: Received JSON: null
                * Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                * -->   JSONArray jsonArray = new JSONArray(respStr);
                *
                * */
                return null;
            }
            JSONArray jsonArray = new JSONArray(respStr);
            // 将json转成list
            parseItems(items, jsonArray);
        } catch (JSONException je) {
            Log.e(TAG, "Failed to parse JSON _ onBackground", je);
        }

        return items;
    }

    @Override
    protected void onPostExecute(List<Recipe> recipes) {
        mExecute.onPostExecute(recipes);
    }

    private void parseItems(List<Recipe> items, JSONArray jsonArray) throws JSONException {
        for (int i = 0; i < jsonArray.length(); i ++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            Recipe recipe = new Recipe();
            recipe.setImage(jsonObject.getString("image"));
            recipe.setReadingNum(jsonObject.getInt("readingNum"));

            jsonObject = jsonObject.getJSONObject("recipe");
            recipe.setId(jsonObject.getInt("ID"));
            recipe.setRecipeName(jsonObject.getString("RecipeName"));
            recipe.setMain(jsonObject.getString("Main"));
            recipe.setSeasoning(jsonObject.getString("Seasoning"));
            recipe.setMethod(jsonObject.getString("Method"));
            recipe.setTips(jsonObject.getString("Tips"));

            /*  获取int值可能出现以下问题...
                org.json.JSONException: Value null at ImgId of type org.json.JSONObject$1 cannot be converted to int
                at org.json.JSON.typeMismatch(JSON.java:100)
            * */
            try {
                recipe.setImgId(jsonObject.getInt("ImgId"));
            } catch (JSONException e) {
                Log.w(TAG, "Failed to parse JSON to ImgId", e);
                recipe.setImgId(0);
            }

            try {
                recipe.setPepperLevel(jsonObject.getInt("PepperLevel"));
            } catch (JSONException e) {
                Log.w(TAG, "Failed to parse JSON to PepperLevel", e);
                recipe.setPepperLevel(0);
            }

            items.add(recipe);
        }
    }

    public void setOnPostExecute(OnPostExecute execute) {
        this.mExecute = execute;
    }

    public interface OnPostExecute {
        void onPostExecute(List<Recipe> recipes);
    }
}
